import $ from "@jquery";

import {
  waitFor,
  getFrameDocument,
  handleDirectionChange,
  extendToolBar,
  handleUserSelectTargetElement,
  getChangeDirectionTarget,
} from "../common";
import { getSelectionElements } from "@utils";

/**
 * 修复文字分割
 * @param {Document} doc
 */
function fixSplitedWord(doc) {
  const selection = doc.getSelection();

  if (!selection.isCollapsed) {
    //顺路处理一下 选择区域的rtl,ltr
    getSelectionElements(doc).forEach((elem) => {
      $(elem).html($(elem).html());
    });
  } else {
    let target = getChangeDirectionTarget(doc);
    $(target).html($(target).html());
  }
}

/**
 * 自定义按钮的点击事件
 * @param {Document} doc
 */
function onCustomButtonClick(doc) {
  $(".custom-button").on("click", function () {
    switch ($(this).attr("id")) {
      case "fix":
        fixSplitedWord(doc);
        break;
      case "rtl":
        handleDirectionChange(doc, "rtl");
        break;
      case "ltr":
        handleDirectionChange(doc, "ltr");
        break;
      default:
        console.error("未知预定义按钮");
        break;
    }
  });
}

function handleEditor(cb) {
  const frameDocument = getFrameDocument();

  frameDocument && cb(frameDocument);

  //3.1 扩展工具栏
  extendToolBar("#edui113");
  //3.2 工具栏按钮事件管理
  onCustomButtonClick(frameDocument);

  //4.内容区域--确定目标元素
  handleUserSelectTargetElement();
}

/**
 *用来对当前document做额外操作的入口
 * @param {Function} cb
 */
export function handleEditorPage(cb) {
  waitFor(() => getFrameDocument(), handleEditor.bind(this, cb));
}
